package com.itcast.peft.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController {

    /**
     * 模型对象
     */
    @Autowired
    private ChatModel chatModel;

    private ChatClient chatClient;

    private ChatMemory chatMemory;

    /**
     * 初始化逻辑
     */
    @PostConstruct
    void init() {
        // 初始化memory
        this.chatMemory = MessageWindowChatMemory.builder().build();
        // 构造client
        this.chatClient = ChatClient.builder(chatModel)
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build()).build();
    }

    @GetMapping("/generate")
    @ResponseBody
    public String generate(String message) {
        var result = chatClient.prompt().user(message).call().content();
        log.info("\n{} -> {}",message, result);
        return result;
    }

    @GetMapping("/clear")
    @ResponseBody
    public String clear() {
        chatMemory.clear(ChatMemory.DEFAULT_CONVERSATION_ID);
        return "success";
    }
}
